<template>
    <div class="adddoctor">
        <page-title>{{type=='edit'?'医生信息编辑':'添加医生'}}</page-title>
        <div class="content-box" style="padding-top: 30px;">    
          <div class="input-box">
            <span class="item-name must-item">医生账号：</span>
            <el-input v-model="params.data.account"></el-input>
          </div>
          <div class="input-box" style="white-space: nowrap;">
            <span class="item-name must-item">医生密码：</span>
            <el-input 
                type="password" 
                v-model="params.data.password"
                :disabled="type=='edit'&&!isModifyPassword"></el-input>
            <el-button 
                @click="modifyPassword"
                type="text" 
                style="margin-left: 5px;"
                v-if="type=='edit'">修改密码</el-button>
          </div>
          <div class="input-box">
            <span class="item-name must-item">医生姓名：</span>
            <el-input v-model="params.data.name"></el-input>
          </div>
          <div class="input-box">
            <span class="item-name must-item" style="position:relative;top:-40px;">医生头像：</span>
            <div class="upload-box">+
              <div class="upload-img-box"
                   v-if="params.data.avatar"
                   :style="'background-image:url('+img_host+params.data.avatar+')'"></div>
              <input type="file" 
                     id="doctorAuditing" 
                     name="file"
                     @change='addImgEvent($event, 1)'
                     accept="image/png, image/jpeg, image/jpg">
            </div>
          </div>
          <div class="input-box">
            <span class="item-name must-item">性别：</span>
            <el-select v-model="params.data.sex" placeholder="请选择">
                <el-option
                  v-for="item in sexOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
          </div>
          <div class="input-box">
            <span class="item-name must-item">年龄：</span>
            <el-input v-model="params.data.age"></el-input>
          </div>
          <div class="input-box">
            <span class="item-name must-item">擅长领域：</span>
            <el-input @focus="dialogVisible=true;" v-model="params.data.domains"></el-input>
          </div>
          <div class="input-box">
            <span class="item-name" style="position:relative;top:-50px;">简介：</span>
            <el-input
              type="textarea"
               v-model="params.data.introduce"
              :rows="3">
            </el-input>
          </div>
          <div class="input-box" style="white-space: nowrap;">
            <span class="item-name must-item">设置问诊费：</span>
            <el-input v-model="params.data.inquiry_price"></el-input>
            <span style="margin-left:20px;margin-right:5px;">高级会员免会诊费</span>
            <el-switch
              v-model="params.data.is_free"
              active-value="1"
              inactive-value="0">
            </el-switch>
          </div>
          <div class="input-box set-time" style="white-space: nowrap;">
            <span class="item-name">设置问诊时间：</span>
            <el-time-picker
                is-range
                arrow-control
                range-separator="-"
                v-model="time"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择问诊时间">
            </el-time-picker>
            <el-input placeholder="设置人数" v-model="stock"></el-input>
            <!-- <el-button>添加问诊时间</el-button> -->
          </div>
          <div class="input-box">
            <span class="item-name" style="position:relative;top:-40px;">凭证：</span>
            <div class="upload-box">+
              <div class="upload-img-box"
                   v-if="params.data.images"
                   :style="'background-image:url('+img_host+params.data.images+')'"></div>
              <input type="file" 
                     id="doctorAuditing" 
                     name="file"
                     @change='addImgEvent($event, 2)'
                     accept="image/png, image/jpeg, image/jpg">
            </div>
          </div>
          <div class="btn-box">
              <el-button @click="addDoctorInfo" type="primary">提交</el-button>
          </div>

        </div>

        <!-- 擅长领域弹框 -->
        <el-dialog
          title="擅长领域"
          :visible.sync="dialogVisible"
          width="70%">
          <div class="content" style="margin-top: 15px;">
              <div class="line" 
                   v-for="item in dataList"
                   :key="item.id">
                  <div class="line-title">{{item.title}} ></div>
                  <div class="line-content">
                    <el-checkbox-group v-model="choosedField">
                      <el-checkbox :label="sub.id"
                                   v-for="sub in item.domainChildren"
                                   :key="sub.id">{{sub.title}}</el-checkbox>
                    </el-checkbox-group>
                  </div>
              </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmChoose">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>
<script>
import * as api from '../../api/api'
import { Message } from 'element-ui'
export default {
    name: 'adddoctor',
    data () {
        return {
            type: '',  //区分添加医生和编辑医生
            time: '',  //医生问诊时间
            timeId: '',  //问诊时间ID
            stock: '',
            //发送请求参数
            params: {
              "model": "Doctors",
              "data": {
                "account": "",
                "password": "",
                "name": "",
                "age": "",
                "sex": "",
                "avatar": "",
                "domains": "",
                "domain_ids": "",
                "introduce": "",
                "inquiry_price": "",
                "is_free": '0',
                "images": "",
                "type": 2
              }
            },
            img_host: '',  //图片域名
            //性别选项
            sexOptions: [
              { value: '1', label: '男'}, 
              { value: '2', label: '女'}
            ],
            isModifyPassword: false,    //是否改了密码
            passwordInputFocus: false,  //密码框聚焦
            doctor_id: '',   //医生ID
            dialogVisible: false,   //擅长领域弹框
            dataList: [],   //擅长领域列表
            choosedField: [],    //选择的擅长领域
            fieldMap: {},    //擅长领域id映射关系
        }
    },
    created() { 
      var that = this;
      that.img_host = 'http://renqing123.oss-cn-shenzhen.aliyuncs.com/';
      that.fetchGoodAtField();
      if (that.$route.query.type === 'edit') {
        that.type = 'edit';
        var docInfo = window.sessionStorage.getItem('edit-doctor');
        docInfo = JSON.parse(docInfo);
        that.doctor_id = docInfo.doctor_id;
        var obj = that.params;
        var keyArr = ['account','name','avatar','sex','age','domains','introduce','inquiry_price','images','password','is_free'];
        keyArr.map(key => {
          obj['data'][key] = docInfo[key];
        });
        that.choosedField = docInfo.domain_ids.split(',');
        if (that.choosedField[0] == '') {
          that.choosedField = [];
        }
        that.params = obj;
        if (docInfo['doctorInquirys'].length > 0) {
          that.stock = docInfo['doctorInquirys'][0]['stock'];
          that.time = [
            new Date(docInfo['doctorInquirys'][0]['inquiry_start_time']), 
            new Date(docInfo['doctorInquirys'][0]['inquiry_end_time'])
          ];
          that.timeId = docInfo['doctorInquirys'][0]['id'];
        }
      }
    },
    methods: {
        //选择图片
        addImgEvent(event, type){
            var that = this;
            var img1 = event.target.files[0];
            //生成临时图片路径
            var temSrc = URL.createObjectURL(img1);
            //判断图片尺寸大小
            var size = img1.size/1024;
            //小于150k
            //if(size>500){
            //    that.imgUpLoading=false;
            //    Message({
            //      showClose: true,
            // /     type: 'error',
            //      message: '图片大小不能大于500KB'
            //    }); 
            //    return false;  
            //};
            //判断图片像素尺寸
            var _img = new Image();
            _img.onload = function  () {
                //that.param.data.avatar = temSrc;
                var formdata = new FormData();
                formdata.append('file', img1);
                api.uploadFile(formdata).then(res => {
                    if (res.data.code == 200) {
                        Message({
                            message: '图片上传成功',
                            type: 'success'
                        });
                        if (type == 1) {
                          that.params.data.avatar = res.data.data;
                        } else {
                          that.params.data.images = res.data.data;
                        }
                        
                    }
                    
                })
                setTimeout(function  () {
                    URL.revokeObjectURL(temSrc);
                },0);
            }
            _img.src = temSrc;
        },
        //添加医生
        addDoctorInfo(){
          var that = this;
          var params = that.params.data;
          //验证资料是否填写完整
          if (!params.account || !params.password || !params.name || !params.age || !params.sex || !params.avatar || !params.domains || !params.inquiry_price) {
            Message({
                message: '请将必填资料填写完整',
                type: 'info',
                duration: 1000
            });
            return;
          }
          //编辑医生信息
          if (that.type == 'edit') {
            
            if (!that.isModifyPassword) {
              delete params['password'];
            }
            api.createData({
              "model": "Doctors",
              "data": params,
              "update_condition": {
                  "doctor_id": that.doctor_id
              }
            }).then( res => {
              if (res.data.code == 200) {
                var _time = that.time;
                if (!!_time && !!that.stock) {
                    var doctor_id = res.data.data;
                    var _start = '';
                    var _end = '';
                    _start = that.formatTime(_time[0]);
                    _end = that.formatTime(_time[1]);
                    api.createData({
                      "model": "DoctorInquirys",
                      "data": {
                        "inquiry_start_time": _start,
                        "inquiry_end_time": _end,
                        "stock": that.stock
                      },
                      "update_condition":{
                        "id": that.timeId
                      }
                    }).then( res => {
                      if (res.data.code == 200) {
                        Message({
                            message: '修改成功',
                            type: 'success',
                            duration: 1000,
                            onClose(){
                              that.$router.push({'name': 'doctorList'});
                            }
                        });
                      }
                    })
                } else {
                  Message({
                      message: '修改成功',
                      type: 'success',
                      duration: 1000,
                      onClose(){
                        that.$router.push({'name': 'doctorList'});
                      }
                  });
                }
                
              }
            })
          } else {
            api.createData(that.params).then(res => {
              if (res.data.code == 200) {
                var doctor_id = res.data.data;
                var _time = that.time;
                var _start = that.formatTime(_time[0]);
                var _end = that.formatTime(_time[1]);
                api.createData({
                  "model": "DoctorInquirys",
                  "data": {
                    "doctor_id": doctor_id,
                    "inquiry_start_time": _start,
                    "inquiry_end_time": _end,
                    "stock": that.stock
                  }
                }).then( res => {
                  if (res.data.code == 200) {
                    Message({
                        message: '添加成功',
                        type: 'success',
                        duration: 1000,
                        onClose(){
                          that.$router.push({'name': 'doctorList'});
                        }
                    });
                  }
                })
              }
            })
          }
        },
        //格式化时间
        formatTime(value){
          var date = new Date(value); 
          var y = date.getFullYear(); 
          var m = date.getMonth() + 1; 
          m = m < 10 ? ('0' + m) : m; 
          var d = date.getDate(); 
          d = d < 10 ? ('0' + d) : d; 
          var h = date.getHours();
          h = h < 10 ? ('0' + h) : h; 
          var minute = date.getMinutes();
          var second = date.getSeconds();
          minute = minute < 10 ? ('0' + minute) : minute; 
          second = second < 10 ? ('0' + second) : second; 
          return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second; 
        },
        //修改密码
        modifyPassword(){
          this.isModifyPassword = true;
          this.params.data.password = '';
        },
        //获取擅长领域
        fetchGoodAtField(){
          var that = this;
          api.getDateList({
            "model": "Domains",
            "with":{
                "0": "domainChildren"
            },
            "limit": 10,
            "offset": 0,
            "orderBy":{

            },
            "condition": {
                "parent_id": 0
            },
            "search":{

            }
          }).then(res => {
            if (res.data.code == 200) {
              var arr = res.data.data.data;
              that.dataList = arr;
              //存放擅长领域id映射关系
              var obj = {};
              arr.map(function (ele, i) {
                ele['domainChildren'].map(function (item) {
                  obj[item.id] = item.title;
                })
              });
              that.fieldMap = obj;
            }
          })
        },
        //确认选择的擅长领域
        confirmChoose(){
          var that = this;
          var obj = that.fieldMap;
          var arr = that.choosedField;
          var domains = '';

          arr.map(function (ele, i) {
            if (i == 0) {
              domains = obj[ele];
            } else {
              domains += (' ' + obj[ele]);
            }
          });

          that.params.data.domains = domains;
          that.params.data.domain_ids = arr.toString();
          that.dialogVisible = false;
        }
    },
    components: {}
}
</script>
<style>
   .adddoctor .el-input {
     width:200px;
   }
   .adddoctor .el-textarea {
    width:200px;
   }
   .set-time .el-input {
    width:100px;
   }
   .set-time .el-date-editor--timerange.el-input__inner {
    width:200px;
   }
   .el-checkbox+.el-checkbox {
       margin-left: 0!important;
   }
   .el-checkbox {
       margin-right: 30px!important;
       line-height: 30px;
   }
   .el-checkbox__input.is-checked .el-checkbox__inner,
   .el-checkbox__input.is-indeterminate .el-checkbox__inner {
     background: #cd4640;
     border-color: #cd4640;
   }
   .el-checkbox__input.is-checked + .el-checkbox__label {
     color: #1f1f1f;
   }
</style>
<style scoped lang="scss">
    .adddoctor {
        .content {
          .line-title,
          .line-content {
            padding: 12px 20px;
          }
          .line:first-of-type>.line-title ,.line:last-of-type{
            border-bottom: 1px solid #ccc;
          }
          .line-title,.line-content{
            border-bottom: 1px solid #e4e7ed;
          }
          .save-btn{
              padding:0 20px 20px;
           }
        }
        background: #ffffff;
        min-height: 100%;
        position: relative;
        box-sizing: border-box;
        padding-bottom: 50px;
        color: #666666;
        font-size: 14px;
        .img-box {
          text-align: center;
          padding-top: 40px;
          padding-bottom: 20px;
          img {
            width:100px;
            height: 100px;
          }
          .img-text {
              padding-top: 5px;
              span {
              color:#1ABC9C;
              font-size: 12px;
              cursor: pointer;
            }
          }
            
        }
        .input-box {
          width: 330px;
          margin: 0 auto 10px;
          .item-name {
            width: 100px;
            display: inline-block;
            color: #666666;
            font-size: 12px;
            text-align: right;
            padding-right: 5px;
          }
          .must-item:before {
            content: '* ';
            color: #F04844;
          }
          .upload-box {
            width: 100px;
            height: 100px;
            display: inline-block;
            border: 1px dashed #dddddd;
            color: #dddddd;
            font-size: 40px;
            text-align: center;
            line-height: 100px;
            position: relative;
            .upload-img-box {
              width:100%;
              height: 100%;
              position: absolute;
              top:0;
              left:0;
              background-size: contain;
              background-position: center center;
              background-repeat: no-repeat;
            }
            input {
              opacity: 0;
              width:100%;
              height: 100%;
              position: absolute;
              top:0;
              left:0;
            }
          }
        }
        .btn-box{
          text-align: center;
          margin-top: 30px;
        }
    }
</style>
